<?php
namespace app\user\controller;

use app\common\controller\Frontend;
use think\Controller;
use think\Config;
use think\Validate;
use think\captcha\Captcha;
use think\Cache;
use think\Session;
use think\Db;
use app\common\model\ActionLog;
use app\common\model\User;

class Login extends Frontend 
{
    public function index(){
        if($this->request->isPost()){
            $data = $this->request->post('',[],'strip_tags');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
                'captcha' => 'require|captcha',
            ];
            $validate = new Validate($rule, [], ['username' => '账户', 'password' => '密码', 'captcha' => '验证码']);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError());
            }
            $user = User::get(['username' => $data['username']]);
            if (!$user) {
                $this->error('登录账号错误');

            }
            if ($user['status'] != '1') {
                $this->error('账号被禁用');

            }
            if ($user->password !== md5(md5($data['password']) . Config::get('auth_key'))) {
                $this->error('登录密码错误 ');
            }
            $user->login_time = time();
            $user->login_ip = request()->ip();
            $user->save();
            Session::set("spadminUser", $user->toArray());
            $actionLog['module'] = 'user';
            $actionLog['method'] = 'post';
            $actionLog['ip'] = $this->request->ip();
            $actionLog['user_agent'] = $this->request->server('HTTP_USER_AGENT');
            $actionLog['action'] = 'login/index';
            $actionLog['type'] = 2;
            $actionLog['username']=$this->request->post('username');
            $actionLog['param'] = '';
            ActionLog::create($actionLog,true);
            $this->success('登录成功');
        }
        $notice = Db::name('Config')->where('name','loginNotice')->value('value');
        $this->assign('notice',$notice);
        return $this->fetch();
    }
}